package com.bwbear.db.splitdb.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

/**
 * @author 张照威
 * @date 2020/8/21
 * @mail 865533614@qq.com
 * @describe
 */
public class MapUtils {

    public static List<String> getLikeByMap(Map<String, Object> map, String keyLike){
        List<String> list=new Vector<>();
        for (Map.Entry<String, Object> entity : map.entrySet()) {
            if(entity.getKey().indexOf(keyLike)>-1){
                list.add((String) entity.getValue());
            }

        }
        return list;
    }

    public static <T> Map<String,T> mmm(Map<String, Object> map,Class<T> tClass,String rootKey,int keyCount,String keyName){
        Map<String,T> outMap = new HashMap<>();
        map.forEach((k,v)->{
            if(k.indexOf(rootKey)>-1){
                String substring = k.substring(rootKey.length() + 1, k.length());
                String[] split = substring.split("\\.");
                String key = "";
                for(int i=0;i<keyCount;i++){
                    key+=split[i];
                }
                if(!outMap.containsKey(key)){
                    try {
                        T t = tClass.getConstructor().newInstance();
                        Field field = tClass.getDeclaredField(keyName);
                        field.setAccessible(true);
                        field.set(t,key);
                        outMap.put(key,t);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                }
                T t = outMap.get(key);
                String fName = "";
                for(int i=keyCount;i<split.length;i++){
                    fName += split[i];
                }
                try {
                    Field field = tClass.getDeclaredField(fName);
                    field.setAccessible(true);
                    field.set(t,v);
                    System.out.println();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        return outMap;
    }

}
